package org.sction.security.encoding;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 作者 : sorc
 * @version 创建时间：2012-11-23 上午11:16:48
 * 
 *          类说明
 */
public class HashCode {
	public final static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String getMD5(String str) {
		return getStringHash(str, "MD5");
	}

	public static String getFileMD5(String path) {
		return getFileHash(new File(path), "MD5");
	}

	public static String getFileMD5(File file) {
		return getFileHash(file, "MD5");
	}

	public static String getStringHash(String str, String hashType) {
		try {
			final MessageDigest md = MessageDigest.getInstance(hashType);
			md.update(str.getBytes());
			final byte[] byteArray = md.digest();
			return toHexString(byteArray);
		} catch (NoSuchAlgorithmException e) {
			return "";
		}

	}

	public static String getFileHash(File file, String hashType) {
		InputStream fis = null;
		BufferedInputStream in = null;
		try {
			fis = new FileInputStream(file);
			in = new BufferedInputStream(fis);
			final MessageDigest md = MessageDigest.getInstance(hashType);
			byte[] buffer = new byte[1024];
			int numRead = 0;
			while ((numRead = in.read(buffer)) > 0) {
				md.update(buffer, 0, numRead);
			}
			return toHexString(md.digest());
		} catch (FileNotFoundException e) {
		} catch (NoSuchAlgorithmException e) {
		} catch (IOException e) {
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static String toHexString(byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}
}
